package com.lingnan.controller;

import com.lingnan.dto.ChatMessageDTO;
import com.lingnan.entity.po.ChatMessage;
import com.lingnan.entity.vo.ChatMessageVO;
import com.lingnan.entity.vo.Result;
import com.lingnan.service.ChatMessageService;
import com.lingnan.service.MessageReadService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat/messages")
@RequiredArgsConstructor
public class ChatMessageController {

    @Resource
    private ChatMessageService messageService;
    @Resource
    private MessageReadService messageReadService;

    /**
    * 发送消息（HTTP备用通道）
    */
    @PostMapping
    public Result<Void> sendMessage(
            @RequestParam("userId") Long userId,
            @RequestParam("userType") Integer userType,
            @RequestBody ChatMessageDTO dto) {
        messageService.sendMessage(dto, userId, userType);
        return Result.ok();
    }

    /**
     * 撤回消息
     */
    @PostMapping("/{messageId}/withdraw")
    public Result<Void> withdrawMessage(
            @RequestParam("operatorId") Long operatorId,
            @PathVariable("messageId") Long messageId) {
        messageService.withdrawMessage(messageId, operatorId);
        return Result.ok();
    }


    /**
     * 获取会话历史
     */
    @GetMapping("/history/{sessionId}")
    public Result<List<ChatMessageVO>> getHistory(
            @RequestParam("userId") Long userId,
            @RequestParam("userType") Integer userType,
            @PathVariable("sessionId") Long sessionId) {
        return Result.ok(
                messageService.getChatHistory(sessionId, userId, userType)
        );
    }


    /**
     * 获取未读消息总数（全局）
     */
    @GetMapping("/unread")
    public Result<Integer> getUnreadCount(
            @RequestParam("userId") Long userId,
            @RequestParam("userType") Integer userType) {
        return Result.ok(
                messageService.getUnreadCount(userId, userType)
        );
    }


    /**
     * 标记消息为已读
     */
    @PostMapping("/read/{sessionId}")
    public Result<Void> markAsRead(
            @RequestParam("userId") Long userId,
            @RequestParam("userType") Integer userType,
            @PathVariable("sessionId") Long sessionId) {
        messageReadService.markMessagesAsRead(sessionId, userId, userType);
        return Result.ok();
    }


    /**
     * 获取最近消息（用于会话预览）
     */
    @GetMapping("/recent/{sessionId}")
    public Result<List<ChatMessage>> getRecentMessages(
            @PathVariable("sessionId") Long sessionId,
            @RequestParam(defaultValue = "10") int limit) {
        return Result.ok(
                messageService.getRecentMessages(sessionId, limit)
        );
    }
}
